package com.duan.laugh.email.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.duan.laugh.email.api.pojo.entity.EmailSendLog;
import com.duan.laugh.email.api.pojo.entity.EmailTemplate;
import com.duan.laugh.email.api.pojo.entity.MailRequest;
import com.duan.laugh.email.service.IEmailSendLogService;
import com.duan.laugh.email.service.IEmailTemplateService;
import com.duan.laugh.email.service.MailService;
import com.duan.laugh.starter.email.EmailAccount;
import com.duan.laugh.starter.email.EmailAccountLocator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.text.StrSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author duanjw
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private EmailAccountLocator emailAccountLocator;
    @Autowired
    private IEmailTemplateService mailTemplateService;
    @Autowired
    private IEmailSendLogService mailSendLogService;

    /**
     * 发送邮件
     *
     * @param mailRequest
     * @return
     */
    @Override
    public boolean sendMail(MailRequest mailRequest) {
        // 多个接受者邮箱用逗号分割
        final String rec = mailRequest.getRec();
        final List<String> tos = Arrays.asList(rec.split(","));
        log.info("共有【{}】个邮件接收者", tos.size());

        // 发送者
        final EmailAccount emailAccount = emailAccountLocator.getEmailAccount(mailRequest.getTenantId());
        // 如果有模板id,根据模板id发送邮件
        final String templateCode = mailRequest.getTemplateCode();

        if (StrUtil.isNotBlank(templateCode)) {
            EmailTemplate mailTemplate = mailTemplateService.getById(Long.valueOf(templateCode));
            String title = mailTemplate.getSubject();
            // 替换邮件内容中的占位符
            final Map paramMap = JSON.parseObject(mailRequest.getParam(), Map.class);
            final String content = new StrSubstitutor(paramMap).replace(mailTemplate.getContent());
            // 发送邮件
            MailUtil.send(emailAccount, tos, title, content, true);
            // 发送记录存入日志表
            saveMailSendLog(emailAccount, rec, mailTemplate.getId(), title, content);
        } else {
            // 发送邮件
            MailUtil.send(emailAccount, tos, mailRequest.getSubject(), mailRequest.getContent(), true);
            // 发送记录存入日志表
            saveMailSendLog(emailAccount, rec, null, mailRequest.getSubject(), mailRequest.getContent());
        }
        log.info("邮件发送成功，邮件请求对象【{}】", mailRequest);
        return true;
    }

    /**
     * 保存邮件发送记录
     *
     * @param emailAccount 发送者
     * @param rec          接收者（逗号分隔）
     * @param templateId   邮件模板id
     * @param title        邮件标题
     * @param content      邮件内容
     */
    private void saveMailSendLog(EmailAccount emailAccount, String rec, Long templateId, String title, String content) {
        mailSendLogService.save(new EmailSendLog()
                .setTemplateId(templateId)
                .setSendPersonEmail(emailAccount.getFrom())
                .setReceivePersonEmail(rec)
                .setSubject(title)
                .setContent(content)
                .setTenantId(emailAccount.getTenantId())
                .setCreateTime(LocalDateTime.now())
                .setSendTime(LocalDateTime.now()));
    }

    /**
     * 发送邮件并记录耗时
     *
     * @param mailRequest
     */
    public void sendMailAndLogTime(MailRequest mailRequest) {
        long startTime = System.currentTimeMillis();
        log.info("监听到邮件发送请求，目标邮箱：【{}】，邮件主题【{}】", mailRequest.getRec(), mailRequest.getSubject());
        this.sendMail(mailRequest);
        long useTime = System.currentTimeMillis() - startTime;
        log.info("邮件发送，耗时【{}】毫秒", useTime);
    }
}
